import { writable, get } from 'svelte/store';
import { invoke } from '@tauri-apps/api/core';
import type { DailyReport, AppSettings } from './types';
import { StorageService } from './storage';

// 创建响应式存储
export const reports = writable<DailyReport[]>([]);
export const currentReport = writable<DailyReport | null>(null);
export const isEditing = writable<boolean>(false);
export const isLoading = writable<boolean>(false);
export const settings = writable<AppSettings>({
  reminderTime: '17:50',
  reminderDays: [1, 2, 3, 4, 5], // 周一到周五
  autoStart: false,
  enableReminder: true,
  autoConvertWeekly: true, // 默认启用自动转换
  showWeeklyNotice: true // 默认显示提醒
});

// 获取存储服务实例
const storage = StorageService.getInstance();

// 辅助函数
export async function createEmptyReport(): Promise<DailyReport> {
  const now = new Date().toISOString();
  const today = await invoke<string>('get_current_date');
  
  return {
    id: crypto.randomUUID(),
    date: today, // 格式：2025年8月19日 周六
    todayWork: '',
    tomorrowPlan: '',
    createdAt: now,
    updatedAt: now
  };
}

// 检查是否应该转换为周计划
export async function checkWeeklyConversion(report: DailyReport): Promise<DailyReport> {
  // 检查用户设置是否启用自动转换
  const currentSettings = get(settings);
  if (!currentSettings.autoConvertWeekly) {
    return report;
  }

  const shouldConvert = await invoke<boolean>('should_convert_to_weekly');
  
  if (shouldConvert && report.tomorrowPlan && !report.weekPlan) {
    const weekRange = await invoke<string>('get_week_range');
    return {
      ...report,
      weekPlan: `下周计划（${weekRange}）:\n${report.tomorrowPlan}`,
      tomorrowPlan: '' // 清空明日计划
    };
  }
  
  return report;
}

// 手动转换明日计划为下周计划
export async function manualConvertToWeekly(report: DailyReport): Promise<DailyReport> {
  if (report.tomorrowPlan && !report.weekPlan) {
    const weekRange = await invoke<string>('get_week_range');
    return {
      ...report,
      weekPlan: `下周计划（${weekRange}）:\n${report.tomorrowPlan}`,
      tomorrowPlan: '' // 清空明日计划
    };
  }
  return report;
}

// 存储操作函数
export const reportActions = {
  // 初始化加载数据
  loadReports: async () => {
    isLoading.set(true);
    try {
      const loadedReports = await storage.loadReports();
      reports.set(loadedReports);
    } catch (error) {
      console.error('Failed to load reports:', error);
    } finally {
      isLoading.set(false);
    }
  },

        // 添加新日报
      addReport: async (report: DailyReport) => {
        try {
          const processedReport = await checkWeeklyConversion(report);
          console.log('Trying to save report:', processedReport);
          const success = await storage.addReport(processedReport);
          console.log('Save result:', success);
          if (success) {
            reports.update(list => [...list, processedReport]);
          }
          return success;
        } catch (error) {
          console.error('Error in addReport:', error);
          return false;
        }
      },
  
  // 更新日报
  updateReport: async (updatedReport: DailyReport) => {
    const processedReport = await checkWeeklyConversion(updatedReport);
    const reportWithTimestamp = { ...processedReport, updatedAt: new Date().toISOString() };
    const success = await storage.updateReport(reportWithTimestamp);
    if (success) {
      reports.update(list => 
        list.map(report => 
          report.id === updatedReport.id ? reportWithTimestamp : report
        )
      );
    }
    return success;
  },

  // 手动转换为周计划
  convertToWeekly: async (reportId: string) => {
    const currentReports = await storage.loadReports();
    const report = currentReports.find(r => r.id === reportId);
    
    if (!report) return false;
    
    const convertedReport = await manualConvertToWeekly(report);
    const success = await storage.updateReport(convertedReport);
    
    if (success) {
      reports.update(list => 
        list.map(r => r.id === reportId ? convertedReport : r)
      );
    }
    
    return success;
  },

        // 复制日报到剪切板
      copyReport: async (report: DailyReport) => {
        const content = `${report.date} 工作日报
一、今日工作汇报
${report.todayWork}

二、明日工作计划
${report.tomorrowPlan}

${report.weekPlan ? `三、下周工作计划\n${report.weekPlan}` : ''}`.trim();
    
    try {
      await invoke('copy_to_clipboard', { text: content });
      return true;
    } catch (error) {
      console.error('复制失败:', error);
      return false;
    }
  },
  
  // 删除日报
  deleteReport: async (id: string) => {
    const success = await storage.deleteReport(id);
    if (success) {
      reports.update(list => list.filter(report => report.id !== id));
    }
    return success;
  },
  
  // 设置当前编辑的日报
  setCurrentReport: (report: DailyReport | null) => {
    currentReport.set(report);
  },
  
  // 设置编辑状态
  setEditing: (editing: boolean) => {
    isEditing.set(editing);
  }
};
